<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="工单信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <px-form-item label="任务单号" prop="workOrderCode">
                  <px-input v-model="formValue.workOrderCode" disabled placeholder="自动生成" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="工单主题" prop="workOrderName">
                  <px-input v-model="formValue.workOrderName" placeholder="主题格式：年/月/日-主题名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="报修人" prop="createName">
                  <px-input v-model="formValue.createName" disabled maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="优先级" prop="weight">
                  <px-select v-model="formValue.weight" filterable clearable placeholder="请选择优先级">
                    <px-option v-for="item in shareData.faultLevelList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="16">
                <px-form-item label="维修时间" prop="time">
                  <px-date-picker
                    v-model="formValue.time"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    type="daterange"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :disabled-date="disabledStartDate"
                    placeholder="请选择维修时间"
                  />
                </px-form-item>
              </px-col>
              <!-- <px-col :span="8">
                <px-form-item label="预计开始时间" prop="planStartTime">
                  <px-date-picker
                    v-model="formValue.planStartTime"
                    value-format="YYYY-MM-DD"
                    type="date"
                    :disabled-date="disabledStartDate"
                    placeholder="请选择预计开始时间"
                    @change="formValue.planEndTime = ''"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="预计结束时间" prop="planEndTime">
                  <px-date-picker
                    v-model="formValue.planEndTime"
                    value-format="YYYY-MM-DD"
                    type="date"
                    :disabled-date="disabledEndDate"
                    placeholder="请选择预计结束时间"
                  />
                </px-form-item>
              </px-col> -->
              <px-col :span="8">
                <px-form-item label="是否消防中断" prop="isStop">
                  <px-radio-group v-model="formValue.isStop">
                    <px-radio :label="1">是</px-radio>
                    <px-radio :label="0">否</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="是否火警隔离" prop="isFireIsolation">
                  <px-radio-group v-model="formValue.isFireIsolation">
                    <px-radio :label="1">是</px-radio>
                    <px-radio :label="0">否</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="执行人" prop="executorInfoList">
                  <px-select-v2
                    v-model="formValue.executorInfoList"
                    multiple
                    filterable
                    clearable
                    :reserve-keyword="false"
                    :options="executorList"
                    placeholder="请选择执行人"
                    @change="executorIdChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="审核人" prop="approverId">
                  <px-select-v2
                    v-model="formValue.approverId"
                    filterable
                    clearable
                    :options="approvalList"
                    placeholder="请选择审核人"
                    @change="approvalIdChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="工单发起方式" prop="createMode">
                  <px-input v-model="formValue.createMode" disabled maxlength="50" clearable />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="设备信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <div style="display: flex">
                  <px-form-item label="故障设备" prop="eqpName">
                    <px-input v-model="formValue.eqpName" disabled placeholder="根据所选故障设备获取" maxlength="50" />
                  </px-form-item>
                  <px-button style="margin-left: 6px" type="primary" :disabled="props.eqpId !== ''" plain @click="dialogVisible = true">
                    选择
                  </px-button>
                </div>
              </px-col>
              <px-col :span="8">
                <px-form-item label="所处地块" prop="eqpFacCodeDesc">
                  <px-input v-model="formValue.eqpFacCodeDesc" disabled placeholder="根据所选故障设备获取" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备位置" prop="positionCodeDesc">
                  <px-input v-model="formValue.positionCodeDesc" disabled placeholder="根据所选故障设备获取" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="问题描述" prop="faultDesc">
                  <px-input
                    v-model="formValue.faultDesc"
                    type="textarea"
                    placeholder="请输入问题描述"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="图片上传" prop="faultImageList">
                  <PhotoUpload
                    v-if="!isMain && !isView"
                    :photoType="photoType"
                    :photoData="{ moduleName: moduleName }"
                    :photoList="formValue.faultImageList"
                    style="margin-bottom: 18px"
                    @changePhotoList="changePhotoList"
                    @savePhotoStatus="savePhotoStatus"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" :disabled="photoStatusFlag" @click="handleSubmit(formRef)">提交</px-button>
    </div>
    <EqpList :visible="dialogVisible" @closeDialog="closeDialog" />
  </div>
</template>
<script setup lang="ts">
import { queryToolLedger } from "@/api/erc/equip";
import { addMaintainList, detailMaintainList, editMaintainList, getModuleName, getWorkOrderCode } from "@/api/erc/maintain";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import dayjs from "dayjs";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import { useRouter } from "vue-router";
import EqpList from "./EqpList.vue";

const router = useRouter();

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "shareData", "taskId", "eqpId", "alarmId", "title"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {},
  photoType: "add",
  moduleName: "",
  photoStatusFlag: false,
  dialogVisible: false,
  executorList: [],
  approvalList: [],
  executorInfoList: [] // 运维组列表
});
const { formValue, photoType, moduleName, photoStatusFlag, dialogVisible, executorList, approvalList, executorInfoList } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  workOrderCode: [{ required: true, message: "任务单号不能为空", trigger: "blur" }],
  workOrderName: [{ required: true, message: "工单主题不能为空", trigger: "blur" }],
  weight: [{ required: true, message: "优先级不能为空", trigger: "change" }],
  time: [{ required: true, message: "请选择维修时间", trigger: "change" }],
  eqpName: [{ required: true, message: "请选择设备", trigger: "change" }],
  // planStartTime: [{ required: true, message: "预计开始时间不能为空", trigger: "blur" }],
  // planEndTime: [{ required: true, message: "预计结束时间不能为空", trigger: "change" }],
  isStop: [{ required: true, message: "是否消防中断不能为空", trigger: "change" }],
  isFireIsolation: [{ required: true, message: "是否火警隔离不能为空", trigger: "change" }],
  executorInfoList: [{ required: true, message: "执行人不能为空", trigger: "change" }],
  approverId: [{ required: true, message: "审核人不能为空", trigger: "change" }],
  eqpId: [{ required: true, message: "故障设备不能为空", trigger: "blur" }],
  faultDesc: [{ required: true, message: "问题描述不能为空", trigger: "blur" }]
}));

// 获取后端自动生成的工单号
const getToolCode = async () => {
  const data = await getWorkOrderCode();
  formValue.value.workOrderCode = data;
};

const disabledStartDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};

const disabledEndDate = (time: Date) => {
  return dayjs(formValue.value.planStartTime).isAfter(dayjs(time.getTime()));
};

const handleGetApprovalList = async () => {
  const res = await getEmployeeIdAndName(["HSE", "ISEP", "ERC&FP"]);
  executorList.value = res;
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  approvalList.value = res?.filter(item => {
    return item.userId !== userInfo.userId;
  });
};

// 获取借用人的名字
const approvalIdChange = val => {
  const arr = approvalList.value?.filter(item => item.value === val);

  if (arr && arr.length > 0) {
    formValue.value.approverName = arr[0].label;
  }
};

// 执行人多选
const executorIdChange = val => {
  const arr = executorList.value?.filter(item => val.some(id => item.value === id));
  if (arr && arr.length > 0) {
    executorInfoList.value = arr?.map(item => ({ executorId: item.value, executorName: item.label }));
    console.log(formValue.value);
  }
};

// 关闭选择设备的弹窗并且拿到选择的数据
const closeDialog = (val?: any) => {
  dialogVisible.value = false;
  if (val) {
    const { eqpId, eqpName, facCode, facName, positionNameAll } = val;
    formValue.value.eqpId = eqpId;
    formValue.value.eqpName = eqpName;
    formValue.value.facCode = facCode;
    formValue.value.eqpFacCodeDesc = facName;
    formValue.value.positionCodeDesc = positionNameAll;
  }
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    getModuleNameValue();
    handleGetApprovalList();
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    formValue.value.createName = `${userInfo.username}-${userInfo.realName}`;
    formValue.value.createBy = userInfo.userId;
    formValue.value.createMode = "PC端发起";
    if (props.drawerType === "add") {
      getToolCode();
      photoType.value = "add";
      const className = localStorage.getItem("className");
      // 如果当前登录人是HSE部门的，则给一个默认值，否则不处理
      if (className === "HSE") {
        formValue.value.executorInfoList = [userInfo.userId];
        executorInfoList.value = [{ executorId: userInfo.userId, executorName: userInfo.realName }];
      }
      // 如果有设备id说明是从报警核查过来的，要去查一下设备的相关信息
      if (props.eqpId) {
        const res = await queryToolLedger({ eqpIdList: [props.eqpId] });
        formValue.value.eqpId = props.eqpId;
        formValue.value.eqpName = res.data[0]?.eqpName;
        formValue.value.facCode = res.data[0]?.facCode;
        formValue.value.eqpFacCodeDesc = res.data[0]?.facName;
        formValue.value.positionCodeDesc = res.data[0]?.positionNameAll;
        formValue.value.relatedOrderNum = props.alarmId;
        formValue.value.maintenanceSource = "ALARM";
        formValue.value.workOrderName = props.title;
      }
    } else if (props.drawerType === "edit") {
      getDetail();
      photoType.value = "edit";
    }
  } else {
    formValue.value = {};
  }
});
// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getModuleName();
  moduleName.value = data;
};

// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.taskId
  };
  const data = await detailMaintainList(params);
  const { executorInfoList: executeList, planEndTime, planStartTime } = data;
  executorInfoList.value = JSON.parse(JSON.stringify(executeList));
  const arr = [];
  executeList.forEach(item => {
    arr.push(item.executorId);
  });
  formValue.value = { ...data, executorInfoList: arr, createMode: "PC端发起", time: [planStartTime, planEndTime] };
  if (data?.faultImageList && data?.faultImageList?.length > 0) {
    data.faultImageList?.forEach(item => {
      item.url = item.fileUrl;
    });
    formValue.value.faultImageList = data.faultImageList;
  } else {
    formValue.value.faultImageList = [];
  }
};
// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
    confirmButtonText: "退出",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      formRef.value.resetFields();
      emits("backMainPage");
    })
    .catch(() => {});
};
// 新的图片列表
const changePhotoList = val => {
  formValue.value.faultImageList = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 提交
const handleSubmit = async (formEl: any, type?: any) => {
  if (!formEl) return;
  const params = formValue.value;
  const imgList = [];
  const { faultImageList, time } = formValue.value;
  if (faultImageList && faultImageList?.length > 0) {
    faultImageList?.forEach(item => {
      if (item?.id) {
        imgList.push(item.id);
      } else if (item?.response.data.id) {
        imgList.push(item.response.data.id);
      }
    });
  }
  await formEl.validate(async valid => {
    if (valid) {
      if (props.drawerType === "add") {
        await addMaintainList({
          ...params,
          faultImageList: imgList,
          executorInfoList: executorInfoList.value,
          planStartTime: time && time[0],
          planEndTime: time && time[1]
        });
        PxMessage.success("创建成功");
        // 如果有传递过来的eqpid说明是报警转过来的
        if (props.eqpId) {
          // await updateAlarm({ alarmId: props.alarmId, alarmStatus: "DONE" });
          router.push("/erc/alarm/realTime");
        }
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        await editMaintainList({
          id: props.taskId,
          ...params,
          faultImageList: imgList,
          executorInfoList: executorInfoList.value,
          planStartTime: time && time[0],
          planEndTime: time && time[1]
        });
        PxMessage.success("编辑成功");
        emits("backMainPage");
        emits("queryTable");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
